from django.shortcuts import render

# 导入modelviewset视图模型
from libs.custom_model_view_set import CustomModelViewSet

# 导入模型
from .models import Department, Project, Server, WorkOrder, MasterVersion

# 导入序列化
from .serializers import DepartmentSerializer, ProjectSerializer, ServerSerializer, WorkOrderSerializer, MasterVersionSerializer

# 导入过滤、搜索和排序插件
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

# 导入drf返回 Response模块
from rest_framework.response import Response

# 导入APIView
from rest_framework.views import APIView

# 导入时间模块
import time
from datetime import date, datetime


class DepartmentViewSet(CustomModelViewSet):
    queryset = Department.objects.all()  # 导入模型类所有数据
    serializer_class = DepartmentSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('name',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '该部门管理关联其他应用，请删除关联的应用再操作'}
        return Response(res)


class ProjectViewSet(CustomModelViewSet):
    queryset = Project.objects.all()  # 导入模型类所有数据
    serializer_class = ProjectSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('name',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '该项目管理关联其他应用，请删除关联的应用再操作'}
        return Response(res)


class ServerViewSet(CustomModelViewSet):
    queryset = Server.objects.all()  # 导入模型类所有数据
    serializer_class = ServerSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('name',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '该服务模块关联其他应用，请删除关联的应用再操作'}
        return Response(res)


class MasterVersionViewSet(CustomModelViewSet):
    queryset = MasterVersion.objects.all()  # 导入模型类所有数据
    serializer_class = MasterVersionSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('name',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '该部门管理关联其他应用，请删除关联的应用再操作'}
        return Response(res)


class WorkOrderViewSet(CustomModelViewSet):
    queryset = WorkOrder.objects.all()  # 导入模型类所有数据
    serializer_class = WorkOrderSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('server', 'master_version', 'applicant')
    search_fields = ('department__name', 'project__name', 'applicant', 'work_order_number', 'processed_people',
                     'fault_description', 'Fault_cause', 'reach', 'version', 'script', 'config',
                     'status', 'priority', 'note')  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "work_order_number"]

    #  update重新更新方法
    def update(self, request, *args, **kwargs):
        # 获取前端提交数据
        status_list = request.data.get('status')
        print(request.data)

        if status_list == '作废':
            self.request.data['status'] = '作废'
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            res = {'code': 200, 'msg': '作废数据更新成功'}
            return Response(res)

        else:
            create_time_list = (request.data.get('create_time'))
            timestamp = datetime.fromisoformat(create_time_list)
            # 将时区信息从datetime对象中移除
            timestamp = timestamp.replace(tzinfo=None)
            # 格式化为所需的格式
            end_time_str = date.strftime(timestamp, '%Y/%m/%d %H:%M:%S')
            # 获取当前时间
            ini_time_str = date.strftime(datetime.now(), '%Y/%m/%d %H:%M:%S')
            # 格式化当前为时间格式
            ini_time = datetime.strptime(ini_time_str, '%Y/%m/%d %H:%M:%S')
            end_time = datetime.strptime(end_time_str, '%Y/%m/%d %H:%M:%S')
            # 计算时间差
            response_time = (ini_time - end_time)
            # 获取时间总数（秒）数
            remaining_seconds = response_time.total_seconds()
            # 通过总秒除以3600， 3600秒为一小时
            corresponding_working_hours = int(remaining_seconds // 3600)
            corresponding_working_hours += 1

            # 赋值
            self.request.data['corresponding_working_hours'] = corresponding_working_hours
            self.request.data['response_time'] = ini_time_str
            self.request.data['processing_time'] = ini_time_str
            print(request.data)
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)

            self.perform_update(serializer)

            res = {'code': 200, 'msg': '更新成功'}
            return Response(res)

    def create(self, request, *args, **kwargs):
        DepartmentiId = int(request.data.get('department'))
        ProjectId = int(request.data.get('project'))
        ServerId = int(request.data.get('server'))
        MasterVersionId = int(request.data.get('master_version'))
        Applicant = request.data.get('applicant')
        WorkOrderNumber = request.data.get('work_order_number')
        FaultDescription = request.data.get('fault_description')
        FaultCause = request.data.get('Fault_cause')
        modify = request.data.get('modify')
        reach = request.data.get('reach')
        version = request.data.get('version')
        script = request.data.get('script')
        config = request.data.get('config')
        status = request.data.get('status')
        priority = request.data.get('priority')
        fallback = request.data.get('fallback')

        # 如果主机存在返回
        WorkOrderNumber_list = WorkOrder.objects.filter(work_order_number=WorkOrderNumber)
        if WorkOrderNumber_list:
            result = {'code': 500, 'msg': '工单已存在'}
            return Response(result)

        # 1. 根据上传ID查询对象
        Departmenti_Id = Department.objects.get(id=DepartmentiId)  # 根据id查询部门
        Project_Id = Project.objects.get(id=ProjectId)  # 根据id查询项目
        Server_Id = Server.objects.get(id=ServerId)  # 根据id查询服务
        Master_Version_Id = MasterVersion.objects.get(id=MasterVersionId)  # 根据id查询版本

        WorkOrder.objects.create(
            department=Departmenti_Id,  # 一对多，传入是一个部门对象
            project=Project_Id,  # 一对多，传入是一个项目对象
            server=Server_Id,  # 一对多，传入是一个服务对象
            master_version=Master_Version_Id, # 一对多，传入是一个版本对象
            applicant=Applicant,
            work_order_number=WorkOrderNumber,
            fault_description=FaultDescription,
            Fault_cause=FaultCause,
            modify=modify,
            reach=reach,
            version=version,
            script=script,
            config=config,
            status=status,
            priority=priority,
            fallback=fallback
        )

        res = {'code': 200, 'msg': '创建成功'}
        return Response(res)


class MyWorkOrderViewSet(CustomModelViewSet):
    queryset = WorkOrder.objects.all()  # 导入模型类所有数据
    serializer_class = WorkOrderSerializer  # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('server', 'master_version', 'processed_people')
    search_fields = ('department__name', 'project__name', 'applicant', 'work_order_number', 'processed_people',
                     'fault_description', 'Fault_cause', 'reach', 'version', 'script', 'config',
                     'status', 'priority', 'note')  # 指定可搜索的字段
    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "work_order_number"]

    #  update重新更新方法
    def update(self, request, *args, **kwargs):
        # 获取前端提交数据
        status_list = request.data.get('status')

        if status_list == '完成':
            end_time_str = request.data.get("processing_time")

            # 获取当前时间
            ini_time_str = date.strftime(datetime.now(), '%Y/%m/%d %H:%M:%S')
            # 格式化当前为时间格式
            ini_time = datetime.strptime(ini_time_str, '%Y/%m/%d %H:%M:%S')
            end_time = datetime.strptime(end_time_str, '%Y/%m/%d %H:%M:%S')
            # 计算时间差
            response_time = (ini_time - end_time)
            # 获取时间总数（秒）数
            remaining_seconds = response_time.total_seconds()
            # 通过总秒除以3600， 3600秒为一小时
            processing_working_hours = int(remaining_seconds // 3600)
            processing_working_hours += 1

            # 赋值
            self.request.data['processing_working_hours'] = processing_working_hours
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            res = {'code': 200, 'msg': '完成成功'}
            return Response(res)

        elif status_list == '分配':
            print(request.data)
            self.request.data['status'] = '处理中'
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            res = {'code': 200, 'msg': '修改更新成功'}
            return Response(res)

        else:
            self.request.data['status'] = '处理中'
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            res = {'code': 200, 'msg': '修改更新成功'}
            return Response(res)


# 仪表盘展示
class WorkOrderEchartViewSet(APIView):
    def get(self, request):
        from datetime import datetime, timedelta
        import pandas as pd

        end = datetime.now()
        start = (end - timedelta(30))
        queryset_obj = WorkOrder.objects.filter(create_time__range=(start, end))  # 或者大于小于 filter(deal_date__gte=week, deal_date__lte=cur_date)


        # 生成时间序列
        date_range = pd.date_range(start=datetime.strftime(start, "%Y-%m-%d"), end=datetime.strftime(end, "%Y-%m-%d"))  # datetime时间转为日期

        x_data = []
        y_success_data = []

        for date in date_range:
            date = datetime.strftime(date, "%Y-%m-%d")
            x_data.append(date)
            y_success_n = 0
            for i in queryset_obj:
                date_time = datetime.strftime(i.create_time, "%Y-%m-%d")
                if date == date_time:
                    y_success_n += 1
            y_success_data.append(y_success_n)
        data = {'y_success_data': y_success_data, 'x_data': x_data}

        res = { 'data': data, 'code': 200, 'msg': '更新成功'}
        return Response(res)